package com.kalix.mplive.answeringQuestion.biz;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.kalix.framework.core.api.persistence.JsonData;
import com.kalix.framework.core.api.persistence.JsonStatus;
import com.kalix.framework.core.impl.biz.ShiroGenericBizServiceImpl;
import com.kalix.framework.core.util.SerializeUtil;
import com.kalix.mplive.answeringQuestion.api.dto.MessageReplyTreeHDTO;
import com.kalix.mplive.answeringQuestion.api.biz.IMessageReplyBeanService;
import com.kalix.mplive.answeringQuestion.api.dao.IMessageReplyBeanDao;
import com.kalix.mplive.answeringQuestion.api.dto.MessageReplyTreeDTO;
import com.kalix.mplive.answeringQuestion.entities.MessageReplyBean;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.persistence.criteria.CriteriaBuilder;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @Description: 留言回复实现类
 * @Author: whw
 * @CreateDate: 2019/10/25$ 10:32$
 * @Version:
 */
public class MessageReplyBeanServiceImpl extends ShiroGenericBizServiceImpl<IMessageReplyBeanDao, MessageReplyBean> implements IMessageReplyBeanService {
    String pathA = "D:\\SystemDownLoads";
    /**

     * @Description: 根据id删除回复
     * @Author: whw
     * @CreateDate: 2019/10/25
     * @Version:
     */
    @Override
    public void deleteAllByPostid(long id) {
        dao.deleteAllByPostid(id);
    }

    /**
     * @Description: 回复“树”
     * @Author: whw
     * @CreateDate: 2019/10/25
     * @Version:
     */
//    @Override
//    public MessageReplyTreeDTO getMessageReplyByPostId(Long messageId, String jsonStr) {
//        MessageReplyTreeDTO messageReplyTreeDTO = new MessageReplyTreeDTO();
//        messageReplyTreeDTO.setId((long)-1);
//        List<MessageReplyBean> mlist = dao.getAll();
//        List<MessageReplyBean> list = mlist.stream().filter(item -> item.getMessageId().longValue() == messageId.longValue() && item.getReplyID() == null).collect(Collectors.toList());
//        messageReplyTreeDTO.setChildren(list);
//        return messageReplyTreeDTO;
//    }
    @Override
    public MessageReplyTreeHDTO getMessageReplyByPostIdH(Long messageId, String jsonStr) {
        MessageReplyTreeHDTO messageReplyTreeDTO = new MessageReplyTreeHDTO();
        messageReplyTreeDTO.setId((long)-1);
        List<MessageReplyBean> mlist = dao.getAll();
        List<MessageReplyBean> list = mlist.stream().filter(item -> item.getMessageId().longValue() == messageId.longValue()).collect(Collectors.toList());
        messageReplyTreeDTO.setChildren(list);
        return messageReplyTreeDTO;
    }

//    @Override
//    public MessageReplyTreeDTO getMessageReplyByPostIdH1(Long messageId, String jsonStr) {
//        MessageReplyTreeDTO messageReplyTreeDTO = new MessageReplyTreeDTO();
//        messageReplyTreeDTO.setId((long)-1);
//        List<MessageReplyBean> mlist = dao.getAll();
//        List<MessageReplyBean> list = mlist.stream().filter(item -> item.getMessageId().longValue() == messageId.longValue() && item.getReplyID() == null).collect(Collectors.toList());
//        List<MessageReplyTreeDTO> mtdList = new ArrayList<>();
//        for (MessageReplyBean m: list) {
//            MessageReplyTreeDTO me = new MessageReplyTreeDTO();
//            List<MessageReplyTreeDTO> slist = getChilden1(m.getId(), mlist);
//            me.setUserName(m.getUserName());
//            me.setReplyMessage(m.getReplyMessage());
////            me.setCreationDate(m.getCreationDate());
//            me.setUpdateDate(m.getUpdateDate());
//            me.setChildren(slist);
//            mtdList.add(me);
//        }
//        messageReplyTreeDTO.setChildren(mtdList);
//        return messageReplyTreeDTO;
//    }

    @Override
    public MessageReplyTreeDTO getMessageReplyByPostId(Long messageId, String jsonStr) {
        Map<String, Object> jsonMap = SerializeUtil.jsonToMap(jsonStr);
        String replyMessage = (String)jsonMap.get("replyMessage");
        MessageReplyTreeDTO root = new MessageReplyTreeDTO();
        root.setId(-1L);
        List<MessageReplyBean> beans = new ArrayList<>();
        String sql = "select r from MessageReplyBean r where 1=1 and r.replyID is null";
        if (replyMessage != null && !replyMessage.isEmpty())  {
            sql += " and r.replyMessage like '%"+replyMessage+"%'";
        }
        if(messageId != -1){
            sql += " and r.messageId =" + messageId;
        }
        sql += " order by r.creationDate desc";
        beans = dao.find(sql);

        if(beans != null && beans.size() > 0){
            List<MessageReplyBean> rootElements = getRootElements(beans);
            if(rootElements != null && rootElements.size() > 0){
                for(MessageReplyBean rootElement:rootElements){
                    Mapper mapper = DozerBeanMapperBuilder.buildDefault();
                    MessageReplyTreeDTO messageReplyTreeDTO = mapper.map(rootElement,MessageReplyTreeDTO.class);
                    messageReplyTreeDTO.setLeaf(rootElement.getIsLeaf() == 0 ? false : true);
                    messageReplyTreeDTO.setParentName("根留言");
                    getChilden(messageReplyTreeDTO, beans, mapper);
                    root.getChildren().add(messageReplyTreeDTO);
                }
            }
        }
        return root;
    }

    /**
     * 递归函数加载子节点
     * @param root
     * @param elements
     */
    private void getChilden(MessageReplyTreeDTO root, List<MessageReplyBean> elements, Mapper mapper){
        List<MessageReplyTreeDTO> children = new ArrayList<MessageReplyTreeDTO>();
        for(MessageReplyBean messageReplyBean : elements){
            if(root.getId() != -1 && (root.getId() == messageReplyBean.getParentId())){
                MessageReplyTreeDTO messageReplyTreeDTO = mapper.map(messageReplyBean,MessageReplyTreeDTO.class);
                messageReplyTreeDTO.setLeaf(messageReplyBean.getIsLeaf() == 0 ? false : true);
                messageReplyTreeDTO.setParentName(root.getUserName());
                children.add(messageReplyTreeDTO);
                if(messageReplyBean.getIsLeaf() == 0){
                    getChilden(messageReplyTreeDTO, elements ,mapper);
                }
            }
        }
        root.setChildren(children);
    }

    /**
     * 递归函数加载子节点
     * @param
     * @param
     */
    private List<MessageReplyTreeDTO> getChilden1(long rid, List<MessageReplyBean> list){
        List<MessageReplyTreeDTO> mlist = new ArrayList<>();
        if (list.size() > 0) {
            for (MessageReplyBean m: list) {
                if (m.getReplyID() != null) {
                    if (m.getReplyID().longValue() == rid) {
                        MessageReplyTreeDTO messageReplyTreeDTO = new MessageReplyTreeDTO();
                        messageReplyTreeDTO.setUserName(m.getUserName());
                        messageReplyTreeDTO.setReplyMessage(m.getReplyMessage());
//                        messageReplyTreeDTO.setCreationDate(m.getCreationDate());
                        messageReplyTreeDTO.setUpdateDate(m.getUpdateDate());
                        List<MessageReplyTreeDTO> melist = getChilden1(m.getId(), list);
                        messageReplyTreeDTO.setChildren(melist);
                        mlist.add(messageReplyTreeDTO);
                    }
                }
            }
        }
        return mlist;
    }

    /**
     * 获得所有根节点
     * @param elements
     * @return
     */

    private List<MessageReplyBean> getRootElements(List<MessageReplyBean> elements) {
        List<MessageReplyBean> roots=new ArrayList<MessageReplyBean>();
        for (MessageReplyBean element : elements) {
            if (element.getParentId() == -1) {
                roots.add(element);
            }
        }
        return roots;
    }

    /**
     * 回复留言
     * @param messageId
     * @param replyMessage
     * @param photo
     */
    @Override
    public void getReplyMessage(String userName ,Long messageId,String replyMessage,String photo,String headportrait,String identity,Boolean judgeIsScore,long userId,int fraction) {
        MessageReplyBean messageReplyBean = new MessageReplyBean();
        messageReplyBean.setMessageId(messageId);
        messageReplyBean.setReplyMessage(replyMessage);
        messageReplyBean.setUserName(userName);
        messageReplyBean.setPhoto(photo);
        messageReplyBean.setFraction(fraction);
        messageReplyBean.setParentId(-1L);
        messageReplyBean.setIsLeaf(0L);
        messageReplyBean.setHeadportrait(headportrait);
        messageReplyBean.setIdentity(identity);
        messageReplyBean.setJudgeIsScore(judgeIsScore);
        messageReplyBean.setUserId(userId);
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = df.format(t);
        try {
            messageReplyBean.setMessageDateTime(df.parse(dateString));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dao.save(messageReplyBean);
    }

    @Override
    public JsonStatus addReplyMessage(MessageReplyBean messageReply) {
        MessageReplyBean messageReplyBean =new MessageReplyBean();
        messageReplyBean.setUserId((long) 0);
        messageReplyBean.setUserName("管理员");
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = df.format(t);
        try {
            messageReplyBean.setUpdateDate(df.parse(dateString));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        messageReply.setMessageId(messageReply.getMessageId());
        messageReplyBean.setPhoto(messageReply.getPhoto());
        messageReplyBean.setParentId(-1L);
        messageReplyBean.setIsLeaf(0L);
        messageReplyBean.setReplyMessage(messageReply.getReplyMessage());
        MessageReplyBean messageReplyBean1 = dao.save(messageReplyBean);
        JsonStatus jsonS = new JsonStatus();
        if (messageReplyBean1 != null) {
            jsonS.setSuccess(true);
            jsonS.setMsg("保存成功！");
        } else {
            jsonS.setFailure(true);
            jsonS.setMsg("保存失败！");
        }
        return jsonS;
    }

    /**
     * 回复回复的回复
     * @param messageId
     * @param replyMessage
     * @param photo
     */
    @Override
    public void getComment(String userName,Long messageId,String replyMessage,String photo,Long replyID,String headportrait,String identity,String repeatName) {
        MessageReplyBean messageReplyBean = new MessageReplyBean();
        messageReplyBean.setMessageId(messageId);
        messageReplyBean.setReplyMessage(replyMessage);
        messageReplyBean.setUserName(userName);
        messageReplyBean.setPhoto(photo);
        messageReplyBean.setReplyID(replyID);
        messageReplyBean.setParentId(-1L);
        messageReplyBean.setIsLeaf(0L);
        messageReplyBean.setHeadportrait(headportrait);
        messageReplyBean.setIdentity(identity);
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = df.format(t);
        try {
            messageReplyBean.setMessageDateTime(df.parse(dateString));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        messageReplyBean.setRepeatName(repeatName);
        dao.save(messageReplyBean);
    }

    @Override
    public JsonData lookMessage(Long messageId, Long replyID) {
        String sql = "select * from mplive_messagereply where messageId='"+messageId+"' and replyID='"+replyID+"'";
        List<MessageReplyBean> list= dao.findByNativeSql(sql, MessageReplyBean.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        return jsonData;
    }

    /**
     * 根据id查询我回复的帖子
     * @param
     * @return
     */
    @Override
    public JsonData getAddComment(Integer uid,Integer num) {
        int max = num*8;
        int min = (num-1)*8;
        List<MessageReplyBean> modelList = dao.findByNativeSql("select * from mplive_messagereply  " +
                "where userId="+uid+" order by messageDateTime DESC limit 8 offset "+ min , MessageReplyBean.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(modelList);
        List<MessageReplyBean> count = dao.findByNativeSql("select * from mplive_messagereply  " +
                "where userId="+uid,MessageReplyBean.class);
        if(count.size()>0){
            jsonData.setTotalCount((long)count.size());
        }
        return jsonData;
    }

    /**
     * 查询共有多少条回复数据
     * @return
     */
    @Override
    public JsonData getMessageReplysum() {
        String sql = "SELECT count (m.replyMessage) FROM MessageReplyBean m";
//        System.out.println(dao.findByNativeSql(sql,MessageBean.class));
        List<MessageReplyBean> list = dao.find(sql);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long) list.size());
        return jsonData;
    }

    /**
     * 分页
     * @param id
     * @return
     */
    @Override
    public JsonData getMessageReplyPostinglist(Integer id,Integer num) {
        int max = num * 10;
        int min = (num-1)* 10;
        List<Integer> listCount = dao.findByNativeSql("select count(id) from mplive_MessageReply M where messageId = "+id,Integer.class);
        if(max>listCount.get(0)){
            max = listCount.get(0);
        }
        String sql = " select * from mplive_messagereply where messageId = "+id+" and replyMessage is not null limit 10 offset "+min;
        List<MessageReplyBean> list = dao.findByNativeSql(sql,MessageReplyBean.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long) list.size());
        return jsonData;
    }

    /**
     * 文件下载
     * @param file
     * @return
     */
    public JsonStatus downloadFile(String file) {
        JsonStatus jsonstatus = new JsonStatus();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        try {
            if (file != null && !file.isEmpty()) {
                String srtname = file.substring(file.lastIndexOf("/") + 1);
                String newFile = file.substring(0, file.lastIndexOf("/")) + "/" + URLEncoder.encode(srtname, "utf-8");
                URL u = new URL(newFile);
                HttpGet httpGet = new HttpGet(newFile);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity entity = httpResponse.getEntity();
                InputStream inStream = entity.getContent();
                byte[] data = readInputStream(inStream);
                String path = getImgPath(file);
                File result = new File(pathA);
                if (!result.exists()) {
                    result.mkdirs();
                }
                String fileName = getImgFileName(file);
                FileOutputStream outStream = new FileOutputStream(result + File.separator + fileName);
                outStream.write(data);
                outStream.flush();
                outStream.close();
            }
            jsonstatus.setSuccess(true);
            jsonstatus.setMsg("下载成功！");

        } catch (Exception e) {
            e.printStackTrace();
            jsonstatus.setFailure(true);
            jsonstatus.setMsg("下载失败");
        }
        return jsonstatus;
    }

    private static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /**
     * 根据url获取文件的路径
     */
    private String getImgPath(String file) {
        return file.substring(file.indexOf("n/") + 1, file.lastIndexOf("/"));
    }
    /**
     * 根据url获取文件的名称
     */
    private String getImgFileName(String file) throws UnsupportedEncodingException {
        String strname = file.substring(file.lastIndexOf("/") + 1);
        return strname;
    }

    @Override
    public JsonData getReplydetails(Long messageId) {
        List<MessageReplyBean> list = dao.find("select f from MessageReplyBean f where messageId="+messageId);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long) list.size());
        return jsonData;
    }
    /**
     * 判断用户是否在改帖下评过分
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData judgeIsScore(long id, long userId) {
        JsonData jsonData = new JsonData();
        List<MessageReplyBean> list = new ArrayList<>();
        if(id!=0&&userId!=0){
            String sql ="select * from mplive_MessageReply where messageId = '"+id+"' and userId = '"+userId+"' and judgeIsScore=true";
            list = dao.findByNativeSql(sql,MessageReplyBean.class);
            jsonData.setTotalCount((long)list.size());
            jsonData.setData(list);
        }
        return jsonData;
    }
}
